package cn.wangfeixiong.util;

import lombok.extern.slf4j.Slf4j;

import java.util.function.Supplier;

@Slf4j
public final class Safe {

    public static void safeRun(Runnable runnable) {
        try {
            runnable.run();
        } catch (Throwable e) {
            log.warn("Safe.safeRun error", e);
        }
    }


    public static void safeRunAny(AnyRun runnable) {
        try {
            runnable.run();
        } catch (Throwable e) {
            log.warn("Safe.safeRun error", e);
        }
    }



    public static void safeRun(Runnable runnable,String errorMsg) {
        try {
            runnable.run();
        } catch (Throwable e) {
            log.warn("{}",errorMsg, e);
        }
    }

    public static void safeRunAny(AnyRun runnable,String errorMsg) {
        try {
            runnable.run();
        } catch (Throwable e) {
            log.warn("{}",errorMsg, e);
        }
    }


    public static <T> T safeGet(Supplier<T> supplier) {
        try {
            return supplier.get();
        } catch (Throwable e) {
            log.warn("Safe.safeGet error", e);
            return null;
        }
    }


    public static void runWithFinalRun(AnyRun run,Runnable finalRun) throws Throwable {
        try {
            run.run();
        }finally {
            finalRun.run();
        }
    }

    public static <T> T getWithFinalRun(AnyCall<T> supplier, Runnable finalRun)throws Throwable {
        try {
           return supplier.call();
        }finally {
            finalRun.run();
        }
    }


    public interface AnyRun{
         void run() throws Throwable;;
    }

    @FunctionalInterface
    public interface AnyCall<T>{
        T call() throws Throwable;;
    }
}
